package com.ids.enigha;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class BroadcastReceiverScreen extends BroadcastReceiver {
	
	public BroadcastReceiverScreen()
	{
		
	}
    @SuppressLint("DefaultLocale")
	public void onReceive(Context context, Intent intent)
	{ 
    	Intent service = new Intent(context, TrackingService.class);
    	
    	SharedPreferences prefs = context.getSharedPreferences("ENIGHA_DETAILS", context.MODE_PRIVATE);
    		
    	System.out.println("raj onReceive.........."+intent.getAction());
    	
    	if(intent.getAction().equals("android.net.conn.CONNECTIVITY_CHANGE"))
    	{
    		if(isTrackingStarted(context))
    		{
	    		System.out.println("raj Is Internet Connected: "+isOnline(context));
				context.stopService(service);
				try{
					Thread.sleep(1000);
				}
				catch(Exception ex)
				{
					
				}
				context.startService(service);
    		}
    	}
    	
		 if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED))
		 {	
			 System.out.println("raj onReceive ACTION_BOOT_COMPLETED");
			 boolean isServicePreviouslyRunning = prefs.getBoolean("isTrackingStarted", false);
			 System.out.println("raj Is Service previously running: "+isServicePreviouslyRunning);
			 if(isServicePreviouslyRunning)
			 {
				 //Intent service = new Intent(context, TrackingService.class);
				 context.startService(service);				 
			 }
		 }
	}
    private Boolean isOnline(Context context) {
		ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE);
        if (connectivity != null)
        {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null)
                for (int i = 0; i < info.length; i++)
                    if (info[i].getState() == NetworkInfo.State.CONNECTED)
                    {
                        return true;
                    }

        }
        return false;
	}
    public boolean isTrackingStarted(Context context)
	{
		SharedPreferences prefs = context.getSharedPreferences("ENIGHA_DETAILS",context.MODE_PRIVATE);
		return prefs.getBoolean("isTrackingStarted", false);
	}
    
}